import * as mongoose from 'mongoose';

// 🆕 简化的提交记录 Schema
export const LcCommitSchema = new mongoose.Schema(
  {
    projectId: {
      type: mongoose.Schema.Types.ObjectId,
      required: true,
      index: true,
    },
    parentCommitId: {
      type: mongoose.Schema.Types.ObjectId,
      required: false,
      index: true,
    },

    // 提交信息
    message: {
      type: String,
      required: true,
    },
    author: {
      userId: { type: Number, required: true, index: true },
      username: { type: String, required: true },
    },
    timestamp: {
      type: Number,
      required: true,
      index: true,
    },

    // 版本类型
    type: {
      type: String,
      enum: ['development', 'release', 'hotfix'],
      required: true,
      index: true,
    },

    // 快照和变更
    snapshot: [
      {
        path: String,
        modify: Number,
        hash: String,
        updateBy: mongoose.Schema.Types.Mixed,
      },
    ],
    changes: [mongoose.Schema.Types.Mixed], // FileChangeWithSide[]
    snapshotIds: [{ type: mongoose.Schema.Types.ObjectId, ref: 'LcFileSnapshot' }],

    // 发布标签
    releaseTag: {
      version: String,
      description: String,
      isActive: { type: Boolean, default: false },
    },

    // 统计信息
    stats: {
      filesChanged: Number,
      additions: Number,
      modifications: Number,
      deletions: Number,
    },

    // 元数据
    meta: {
      tags: [String],
      aiAgent: String,
      collaborationId: String,
    },
  },
  {
    timestamps: true,
    collection: 'lc_commits',
  },
);

// 🆕 文件副本表 Schema
export const LcFileSnapshotSchema = new mongoose.Schema(
  {
    hash: {
      type: String,
      required: true,
      index: true, // 用于去重查询
    },
    type: {
      type: String,
      enum: ['document', 'type', 'project'],
      required: true,
      index: true,
    },
    data: {
      type: mongoose.Schema.Types.Mixed,
      required: true,
    },

    // 元数据
    projectId: {
      type: mongoose.Schema.Types.ObjectId,
      required: true,
      index: true,
    },
    originalId: {
      type: String,
      required: true,
    },
    path: {
      type: String,
      required: true,
    },
    createTime: {
      type: Number,
      default: Date.now,
      index: true, // 用于清理过期数据
    },
    size: {
      type: Number,
      required: true,
    },
  },
  {
    timestamps: true,
    collection: 'lc_file_snapshots',
  },
);

// 🆕 项目版本状态表 Schema
export const ProjectVersionStateSchema = new mongoose.Schema(
  {
    projectId: {
      type: mongoose.Schema.Types.ObjectId,
      required: true,
      unique: true, // 每个项目只有一个版本状态记录
      index: true,
    },

    // 当前开发版本
    developmentCommitId: {
      type: mongoose.Schema.Types.ObjectId,
      required: false,
      ref: 'LcCommit',
    },

    // 当前发布版本
    releaseCommitId: {
      type: mongoose.Schema.Types.ObjectId,
      required: false,
      ref: 'LcCommit',
    },
    releaseVersion: {
      type: String,
      required: false,
    },

    // 时间信息
    createTime: {
      type: Number,
      default: Date.now,
    },
    updateTime: {
      type: Number,
      default: Date.now,
    },
  },
  {
    timestamps: true,
    collection: 'project_version_states',
  },
);

// 🆕 创建复合索引
LcCommitSchema.index({ projectId: 1, type: 1, timestamp: -1 });
LcCommitSchema.index({ projectId: 1, timestamp: -1 });
LcCommitSchema.index({ projectId: 1, parentCommitId: 1 });
LcCommitSchema.index({ projectId: 1, 'releaseTag.isActive': 1 }); // 查找活跃发布版本

LcFileSnapshotSchema.index({ hash: 1, projectId: 1 }); // 去重查询
LcFileSnapshotSchema.index({ projectId: 1, type: 1 }); // 按项目和类型查询
LcFileSnapshotSchema.index({ createTime: 1 }); // 清理过期数据

ProjectVersionStateSchema.index({ projectId: 1 }, { unique: true });

// 🆕 静态方法
LcCommitSchema.statics = {
  // 获取项目的提交历史
  async getCommitHistory(options: {
    projectId: string;
    type?: 'development' | 'release' | 'hotfix';
    limit?: number;
    skip?: number;
  }) {
    const query: any = { projectId: new mongoose.Types.ObjectId(options.projectId) };

    if (options.type) {
      query.type = options.type;
    }

    const total = await this.countDocuments(query);
    const commits = await this.find(query)
      .sort({ timestamp: -1 })
      .skip(options.skip || 0)
      .limit(options.limit || 20)
      .lean();

    return {
      commits,
      total,
      hasMore: total > (options.skip || 0) + (options.limit || 20),
    };
  },

  // 获取活跃的发布版本
  async getActiveRelease(projectId: string) {
    return this.findOne({
      projectId: new mongoose.Types.ObjectId(projectId),
      type: 'release',
      'releaseTag.isActive': true,
    });
  },
};

// 🆕 实例方法
LcCommitSchema.methods = {
  // 获取提交的完整信息
  async getFullInfo() {
    return {
      ...this.toObject(),
      // 可以添加其他关联信息
    };
  },
};

// 🆕 文件变更记录 Schema
export const LcFileChangeSchema = new mongoose.Schema(
  {
    projectId: {
      type: String,
      required: true,
      index: true,
    },
    path: {
      type: String,
      required: true,
      index: true,
    },
    action: {
      type: String,
      required: true,
      enum: ['add', 'modify', 'delete'],
      index: true,
    },
    version: {
      type: Number,
      required: true,
      default: 1,
    },
    // 🆕 变更类型：快照或补丁
    changeType: {
      type: String,
      required: true,
      enum: ['snapshot', 'patch'],
      default: 'patch',
    },
    timestamp: {
      type: Number,
      required: true,
      index: true,
    },
    author: {
      type: String,
      required: false,
    },
    userId: {
      type: Number,
      required: true,
      index: true,
    },
    message: {
      type: String,
      required: false,
    },
    content: {
      type: String,
      required: false, // 仅快照有完整内容
    },
    previousContent: {
      type: String,
      required: false,
    },
    // 🆕 补丁相关字段
    patch: {
      type: String,
      required: false, // 仅补丁有差异数据
    },
    baseVersion: {
      type: Number,
      required: false, // 补丁指向的基础快照版本
    },
    contentHash: {
      type: String,
      required: false,
    },
    fileSize: {
      type: Number,
      required: false,
      default: 0,
    },
    stats: {
      linesAdded: { type: Number, default: 0 },
      linesDeleted: { type: Number, default: 0 },
      linesModified: { type: Number, default: 0 },
    },
    meta: {
      type: { type: String },
      source: { type: String },
      clientInfo: { type: String },
    },
  },
  {
    collection: 'file_changes',
    timestamps: { createdAt: 'create_time', updatedAt: 'update_time' },
  },
);

// 创建复合索引以优化查询性能
LcFileChangeSchema.index({ projectId: 1, timestamp: -1 }); // 项目+时间倒序
LcFileChangeSchema.index({ projectId: 1, path: 1, timestamp: -1 }); // 项目+路径+时间倒序
LcFileChangeSchema.index({ projectId: 1, userId: 1, timestamp: -1 }); // 项目+用户+时间倒序
LcFileChangeSchema.index({ projectId: 1, action: 1, timestamp: -1 }); // 项目+操作类型+时间倒序
